package api

import (
	"awesomeProject/user-web/forms"
	"context"
	"fmt"
	"math/rand"
	"net/http"
	"strings"
	"time"

	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"

	"awesomeProject/user-web/global"
)

func GenerateSmsCode(width int) string {
	//生成width长度的短信验证码

	numeric := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	r := len(numeric)
	rand.Seed(time.Now().UnixNano())

	var sb strings.Builder
	for i := 0; i < width; i++ {
		fmt.Fprintf(&sb, "%d", numeric[rand.Intn(r)])
	}
	return sb.String()
}

func SendSms(ctx *gin.Context) {
	// 进行验证
	sendSmsForm := forms.SendSmsForm{}
	if err := ctx.ShouldBind(&sendSmsForm); err != nil {
		HandleValidateError(err, ctx)
		return
	}

	smsCode := GenerateSmsCode(6) // 随机创建验证码
	accessKeyId := global.ServerConfig.AliSmsInfo.ApiKey
	accessKeySecret := global.ServerConfig.AliSmsInfo.ApiSecret

	client, err := dysmsapi.NewClientWithAccessKey("cn-hangzhou", accessKeyId, accessKeySecret)
	if err != nil {
		panic(fmt.Sprintf("初始化客户端失败: %v", err))
	}
	// 构建请求对象
	request := dysmsapi.CreateSendSmsRequest()
	request.Scheme = "https"                 // 强制使用HTTPS协议[7](@ref)
	request.PhoneNumbers = sendSmsForm.Phone // 目标手机号（多个用逗号分隔）
	request.SignName = "阿里云短信测试"
	request.TemplateCode = "SMS_154950909"
	request.TemplateParam = fmt.Sprintf(`{"code":"%s"}`, smsCode) // JSON格式参数

	// 发送请求
	_, err = client.SendSms(request)
	if err != nil {
		panic(fmt.Sprintf("发送失败: %v", err))
	}

	//将验证码保存起来 - redis
	rdb := redis.NewClient(&redis.Options{
		Addr: fmt.Sprintf("%s:%d", global.ServerConfig.RedisInfo.Host, global.ServerConfig.RedisInfo.Port),
	})

	rdb.Set(context.Background(), sendSmsForm.Phone, smsCode, 300*time.Second)
	ctx.JSON(http.StatusOK, gin.H{
		"msg": "发送成功",
	})
}
